﻿using System.IO;
using UnityEditor;
using UnityEditor.AssetImporters;
using UnityEditor.ProjectWindowCallback;
using UnityEngine;
using winS.Unity.Process;

namespace winS.UnityEditor.ProcessEditor
{
    [ScriptedImporter(1, extension)]
    public class ProcessImporter : ScriptedImporter
    {
        public const string extension = "process";

        public static Texture2D icon => Resources.Load<Texture2D>("winS.UnityEditor.ProcessEditor/Icons/Icon");

        [MenuItem("Assets/Create/Process Editor/Process", false)]
        private static void CreateNewProcess()
        {
            string name = $"New Process.{extension}";
            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<Creator>(), name, icon, null);
        }

        public override void OnImportAsset(AssetImportContext assetImportContext)
        {
            TextAsset textAsset = new TextAsset(File.ReadAllText(assetImportContext.assetPath));
            assetImportContext.AddObjectToAsset("main obj", textAsset, icon);
            assetImportContext.SetMainObject(textAsset);
        }

        internal class Creator : EndNameEditAction
        {
            public override void Action(int instanceId, string pathName, string resourceFile)
            {
                EditorProcessAssetManager.Create<Process>(EditorAssetManager.ProjectPathToFullPath(pathName));
                EditorAssetManager.Refresh();
            }
        }
    }
}